package com.sdjzu.wangfuying.disableautobrightness.service;

import android.accessibilityservice.AccessibilityService;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import android.widget.Toast;

import com.sdjzu.wangfuying.disableautobrightness.R;
import com.sdjzu.wangfuying.disableautobrightness.annotation.Performance;
import com.sdjzu.wangfuying.disableautobrightness.util.BrightnessUtil;
import com.sdjzu.wangfuying.disableautobrightness.util.GameModeUtil;

import java.util.Locale;

import androidx.core.app.NotificationCompat;

import static android.view.accessibility.AccessibilityEvent.TYPE_VIEW_CLICKED;
import static android.view.accessibility.AccessibilityEvent.TYPE_VIEW_LONG_CLICKED;
import static android.view.accessibility.AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED;
import static com.sdjzu.wangfuying.disableautobrightness.Config.BROADCAST_INTENT;
import static com.sdjzu.wangfuying.disableautobrightness.Config.showStateChangedToast;
import static com.sdjzu.wangfuying.disableautobrightness.util.GameModeUtil.isGameMode;

public class ActivityMonitorServiceV10 extends AccessibilityService {
    private static final String TAG = "ActivityMonitorService";
    private static final int NOTIFICATION_ID = 1000;
    private static final String CHANNEL_ID = "status";
    private CharSequence mWindowClassName;
    private String mLastPackage;
    private boolean mAutoBrightness = false;
    private boolean isInGameMode = false;
    private SharedPreferences prefs;
    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BROADCAST_INTENT.equals(action)) {
                Log.d(TAG, "收到了更新请求！");
            }
        }
    };

    public ActivityMonitorServiceV10() {
    }

    //初始化
    @Override
    protected void onServiceConnected() {
        super.onServiceConnected();
        // bind broadcast receiver
        IntentFilter filter = new IntentFilter();
        filter.addAction(BROADCAST_INTENT);
        registerReceiver(mBroadcastReceiver, filter);
        // create notification channel if need
        createNotificationChannel();
        // load pref
        prefs = PreferenceManager.getDefaultSharedPreferences(this);
        prefs.edit().putBoolean("test", true).apply();
        Toast.makeText(this, "辅助服务已开启", Toast.LENGTH_SHORT).show();
    }

    @SuppressLint("SwitchIntDef")
    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        int type = event.getEventType();
        switch (type) {
            case TYPE_WINDOW_STATE_CHANGED:
                mWindowClassName = event.getClassName();
                String currentPackage = event.getPackageName() == null ? "" : event.getPackageName().toString();
                Log.d(TAG, currentPackage);
                // do next actions
                if (!currentPackage.isEmpty()) configAutoBrightness(currentPackage);
                break;
            case TYPE_VIEW_CLICKED:
            case TYPE_VIEW_LONG_CLICKED:
                break;
            default:
                break;
        }
    }

    @Performance
    private void configAutoBrightness(String currentPackage) {
        // 去重
        if (!currentPackage.equals(mLastPackage)) {
            // 过滤掉系统界面
            if ("com.android.systemui".equals(currentPackage)) return;
            boolean isGameNow = isGameMode(this, currentPackage);
            boolean isGameLast = isGameMode(this, mLastPackage);
            mLastPackage = currentPackage;
            if (isGameNow && !isGameLast) {
                // enter game mode
                mAutoBrightness = BrightnessUtil.isAutoBrightness(this);
                if (mAutoBrightness) {
                    // disable auto brightness
                    if (!BrightnessUtil.autoBrightness(this, false)) {
                        Toast.makeText(getBaseContext(), R.string.service_monitor_enter_game_mode_failed, Toast.LENGTH_SHORT).show();
                    } else {
                        int brightnessLevel = 0;
                        if (-1 != (brightnessLevel = GameModeUtil.getBrightnessLevel(this, currentPackage))) {
                            BrightnessUtil.saveBrightness(this, brightnessLevel);
                            Log.d(TAG, "saveBrightness: " + brightnessLevel);
                        }
                        notification(currentPackage, true);
                        LogServiceIsNotAService.getInstance().add(mLastPackage, "切换到白名单App，进入游戏模式");
                        if (showStateChangedToast)
                            if (prefs.getBoolean("pref_setting_key_use_toast", false))
                                Toast.makeText(getBaseContext(), R.string.service_monitor_enter_game_mode_ok, Toast.LENGTH_SHORT).show();
                        Log.d(TAG, "isAutoBrightness: " + BrightnessUtil.isAutoBrightness(this));
                    }
                } else {
                    Log.d(TAG, "当前用户已经关闭了自动亮度功能，并不需要重新设置了");
                }
            } else if (!isGameNow && isGameLast) {
                // exit game mode
                notification(currentPackage, false);
                if (mAutoBrightness) {
                    if (!BrightnessUtil.autoBrightness(getBaseContext(), mAutoBrightness)) {
                        Toast.makeText(getBaseContext(), R.string.service_monitor_exit_game_mode_failed, Toast.LENGTH_SHORT).show();
                    } else {
                        LogServiceIsNotAService.getInstance().add(mLastPackage, "切换到非白名单App，退出游戏模式");
                        if (showStateChangedToast)
                            if (prefs.getBoolean("pref_setting_key_use_toast", false))
                                Toast.makeText(getBaseContext(), R.string.service_monitor_exit_game_mode_ok, Toast.LENGTH_SHORT).show();
                    }
                }
            }
        }
    }

    @TargetApi(Build.VERSION_CODES.O)
    private void createNotificationChannel() {
        NotificationChannel channel = new NotificationChannel(CHANNEL_ID, getText(R.string.service_monitor_notification_channel_name), NotificationManager.IMPORTANCE_DEFAULT);
        NotificationManager notificationManager = (NotificationManager) getSystemService(
                NOTIFICATION_SERVICE);
        notificationManager.createNotificationChannel(channel);
    }

    private void notification(String appName, boolean enter) {
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        if (enter && prefs.getBoolean("pref_setting_key_use_notification", false)) {
            Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                    .setContentTitle(getText(R.string.service_monitor_notification_channel_name))
                    .setContentText(String.format(Locale.getDefault(), "%s %s工作模式", appName, enter ? "进入" : "退出"))
                    .setWhen(System.currentTimeMillis())
                    .setSmallIcon(R.drawable.icon)
                    .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.icon))
                    .setAutoCancel(false)
                    //.setContentIntent()
                    .build();
            manager.notify(NOTIFICATION_ID, notification);
        } else {
            manager.cancel(NOTIFICATION_ID);
        }
    }

    @Override
    public void onInterrupt() {
        unregisterReceiver(mBroadcastReceiver);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        onInterrupt();
    }
}
